<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Design Tool ,yingyong=yingyong01&kuan=800&gao=600</title>
    <link href="./css/prism.min.css" rel="stylesheet" />
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: auto;
        }
        .top-section {
            display: flex;
            height: 1080px;
        }
        .bottom-section {
            top: -30px;
            display: flex;
            height: 600px;
        }
        .sidebar {
            width: 13%;
            background-color: #f4f4f4;
            padding: 2px;
            box-sizing: border-box;
            height: 1080px;
            overflow: auto;
        }
        .main-content {
            width: 67%;
            background-color: #fff;
            padding: 2px;
            box-sizing: border-box;
            border-left: 1px solid #ddd;
            border-right: 1px solid #ddd;
            overflow: auto;
        }
        .property-panel {
            width: 20%;
            background-color: #f4f4f4;
            padding: 1px;
            box-sizing: border-box;
            height: 1080px;
            overflow: auto;
        }
        .code-section {
            width: 25%;
            height:500px;
            background-color: rgba(255, 250, 173, 0.64);
            padding: 20px;
            box-sizing: border-box;
            /*overflow-y: auto;*/
        }

        textarea {
            width: 100%;
            height: 80%;
            box-sizing: border-box;
            overflow-x: auto;
            white-space: nowrap;
            background-color: lightblue;
        }
    </style>

    <script>
        function isEmptyObject(obj) {
            return Object.keys(obj).length === 0 && obj.constructor === Object;
        }

        function getQueryParams() {
            const queryParams = {};
            const queryString = window.location.search.substring(1);
            const paramsArray = queryString.split('&');

            paramsArray.forEach(param => {
                if (param) {
                    const [key, value] = param.split('=');
                    queryParams[key] = decodeURIComponent(value || '');
                }
            });

            return queryParams;
        }

        // 示例用法
        const params = getQueryParams();
        console.log(params); // 输出: { key1: 'value1', key2: 'value2' }
        if (isEmptyObject(params)){
            alert("需要输入参数！")
        }
        var v_yingyongname=params['yingyong'];

        console.log(v_yingyongname);
        var v_kuan=params['kuan'];
        var v_gao=params['gao'];

        function loadFileFromUrl(file_url,target) {
            const url = file_url;
            if (!url) {
                alert("Please enter a valid URL.");
                return;
            }
            fetch(url).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.text();
            }).then(data => {
                document.getElementById(target).value=data;
            }).catch(error => {
                console.error("There was a problem with the fetch operation:", error);
                alert("Failed to load file from URL. Please check the URL and try again.");
            });
        }
    </script>

</head>
<body>
<div class="top-section">
    <div class="sidebar">
        <iframe src="./design/elements.html" style="width:100%;height:1080px;overflow: auto;">

        </iframe>
    </div>
    <div class="main-content" id="design-canvas" ondrop="drop(event)" ondragover="allowDrop(event)">

        <iframe id="dynamicIframe" src="" style="overflow: hidden; /* 添加滚动条 */">

        </iframe>
        <script>
            function loadIframe() {
                const url = "./design/designer.html"+'?yingyong='+v_yingyongname+'&kuan='+v_kuan+'&gao='+v_gao;
                if (url) {
                    const iframe = document.getElementById('dynamicIframe');
                    iframe.style.width = v_kuan+'px';
                    iframe.style.height = v_gao+'px';
                    iframe.src = url;
                } else {
                    alert('Please enter a valid URL.');
                }
            }
            loadIframe();
        </script>
    </div>
    <div class="property-panel">
        <div id="properties">
            <!-- Properties will be shown here based on selected component -->
            <iframe src="./design/shuxings.html" style="width:100%;height:1080px;overflow: auto; /* 添加滚动条 */">
            </iframe>
        </div>
    </div>
</div>
<div class="bottom-section">

    <div class="code-section">
        <div style="display:flex;align:center;">
            <h3>应用框架代码</h3>
            <button onclick="save()" style="height:50%;">保存</button>
        </div>
        <textarea id="framework-code">
        </textarea>
        <button onclick="kuangjiayulan()">代码格式化预览</button>
    </div>

    <div class="code-section">
        <h3>应用html代码</h3>
        <textarea id="html-code">
        </textarea>
        <button onclick="htmlyulan()">代码格式化预览</button>

    </div>
    <div class="code-section">
        <h3>应用CSS</h3>
        <textarea id="css-code">
        </textarea>
        <button onclick="cssyulan()">代码格式化预览</button>

    </div>
    <div class="code-section">
        <h3>应用JS</h3>

        <textarea id="js-code">
        </textarea>
        <button onclick="jsyulan()">代码格式化预览</button>

    </div>
</div>
<pre><code id="codeOutput" class="language-js"></code></pre>
<script src="./js/prism.min.js"></script>
<script>
    function save(){
        const inputData = {
            'yyid':v_yingyongname,
            'index_content':document.getElementById('framework-code').value,
            'html_content':document.getElementById('html-code').value,
            'css_content':document.getElementById('css-code').value,
            'js_content':document.getElementById('js-code').value
        }
        fetch('/shujuzhanshi/yingyong_save/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ inputData })
        })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                alert(data.message);
            })
            .catch((error) => {
                console.error('Error:', error);
                alert(error);
            });
    }

    function allowDrop(ev) {
        ev.preventDefault();
    }

    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.getAttribute('data-component-type'));
    }

    function drop(ev) {
        ev.preventDefault();
        var type = ev.dataTransfer.getData("text");
        var newElement;

        if (type === "button") {
            newElement = document.createElement("button");
            newElement.textContent = "New Button";
            newElement.style.marginBottom = "10px";
        } else if (type === "text") {
            newElement = document.createElement("p");
            newElement.textContent = "New Text";
            newElement.style.marginBottom = "10px";
        }

        // Append the new element to the design canvas
        ev.target.appendChild(newElement);

        // Set up event listener for selecting the component
        newElement.addEventListener('click', () => {
            showProperties(newElement);
        });
    }

    function showProperties(element) {
        const propertiesDiv = document.getElementById('properties');
        propertiesDiv.innerHTML = '';

        if (element.tagName.toLowerCase() === 'button') {
            propertiesDiv.innerHTML += `
                    <label>Name:</label><br>
                    <input type="text" value="${element.textContent}" onchange="updateProperty(this, '${element.id}', 'textContent')"><br>
                    <label>Background Color:</label><br>
                    <input type="color" value="${element.style.backgroundColor || '#ffffff'}" onchange="updateProperty(this, '${element.id}', 'backgroundColor')">
                `;
        } else if (element.tagName.toLowerCase() === 'p') {
            propertiesDiv.innerHTML += `
                    <label>Text:</label><br>
                    <input type="text" value="${element.textContent}" onchange="updateProperty(this, '${element.id}', 'textContent')"><br>
                    <label>Color:</label><br>
                    <input type="color" value="${element.style.color || '#000000'}" onchange="updateProperty(this, '${element.id}', 'color')">
                `;
        }

        // Assign a unique ID to the element if it doesn't have one
        if (!element.id) {
            element.id = 'comp-' + Date.now().toString(36);
        }
    }

    function updateProperty(input, elementId, property) {
        const element = document.getElementById(elementId);
        element.style[property] = input.value;
    }

    // Example of updating code sections
    function updateCodeSections() {
        const frameworkCode = document.getElementById('framework-code');
        const htmlCode = document.getElementById('html-code');
        const cssCode = document.getElementById('css-code');
        const jsCode = document.getElementById('js-code');


        var fileurl = "./yingyongs/"+v_yingyongname+'/index.html' ;
        loadFileFromUrl(fileurl,'framework-code');
        var fileurl = "./yingyongs/"+v_yingyongname+'/'+v_yingyongname+'.html';
        loadFileFromUrl(fileurl,'html-code');
        var fileurl = "./yingyongs/"+v_yingyongname+'/'+v_yingyongname+'.css';
        loadFileFromUrl(fileurl,'css-code');
        var fileurl = "./yingyongs/"+v_yingyongname+'/'+v_yingyongname+'.js';
        loadFileFromUrl(fileurl,'js-code');

    }
    document.getElementById('framework-code').addEventListener('click', function() {
        // Split the text by newline characters
        let lines = this.value.split('\n');
        // Filter out empty lines
        lines = lines.filter(line=>line.trim() !== '');
        // Join the lines back together with a newline character
        this.value = lines.join('\n');
    });
    document.getElementById('js-code').addEventListener('click', function() {
        // Split the text by newline characters
        let lines = this.value.split('\n');
        // Filter out empty lines
        lines = lines.filter(line=>line.trim() !== '');
        // Join the lines back together with a newline character
        this.value = lines.join('\n');
    });
    document.getElementById('html-code').addEventListener('click', function() {
        // Split the text by newline characters
        let lines = this.value.split('\n');
        // Filter out empty lines
        lines = lines.filter(line=>line.trim() !== '');
        // Join the lines back together with a newline character
        this.value = lines.join('\n');
    });
    document.getElementById('css-code').addEventListener('click', function() {
        // Split the text by newline characters
        let lines = this.value.split('\n');
        // Filter out empty lines
        lines = lines.filter(line=>line.trim() !== '');
        // Join the lines back together with a newline character
        this.value = lines.join('\n');
    });
    // Initialize code sections with example content
    window.onload = updateCodeSections;
    function kuangjiayulan(){
        highlightCode("framework-code","codeOutput","language-html");
    }
    function htmlyulan(){
        highlightCode("html-code","codeOutput","language-html");
    }
    function cssyulan(){
        highlightCode("css-code","codeOutput","language-css");
    }
    function jsyulan(){
        highlightCode("js-code","codeOutput","language-js");
    }

    function highlightCode(sourceID,outputId,classtype) {
        const codeInput = document.getElementById(sourceID).value;
        const codeOutput = document.getElementById(outputId);
        codeOutput.class = classtype;
        codeOutput.textContent = codeInput;
        Prism.highlightElement(codeOutput);
    }

</script>
</body>
</html>



